package com.ruoyi.framework.config.properties;

import com.ruoyi.framework.config.KeycloakAdminApiConfig;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.keycloak.representations.idm.ClientRepresentation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
@Data
@Slf4j
public class KeycloakConfig {

    @Resource
    private KeycloakAdminApiConfig keycloakAdminApiConfig;

    @Value("${spring.security.oauth2.client.registration.keycloak.provider}")
    private String provider = "keycloak";

    @Value("${spring.security.oauth2.client.registration.keycloak.client-id}")
    private String clientId;

    @Value("${spring.security.oauth2.client.provider.keycloak.jwk-set-uri}")
    private String jwkSetUri;

    @Value("${spring.security.oauth2.client.provider.keycloak.issuer-uri}")
    private String issuerUri;

    @Value("${oauth2.logout-success-url}")
    private String logoutSuccessUrl;

    // 从keycloak的客户端配置中获取应用前端访问地址，用于注销成功后跳转。也可根据实际情况采用其他方式获取前端地址
    public String getFrontUrl(){
        try {
            List<ClientRepresentation> clients = keycloakAdminApiConfig.realmResource().clients().findByClientId(clientId);
            if (clients != null && !clients.isEmpty()) {
                ClientRepresentation client = clients.get(0);
                return client.getBaseUrl();
            }
        } catch (Exception e){
            log.error("keycloak 获取前端地址失败", e);
        }
        return "";
    }
}
